﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace

#if DATA
SharpSoft.Data
#else
SharpSoft
#endif

{
    /// <summary>
    /// 带有状态的模型基类，实现了<see cref="INotifyPropertyChanged"/>,且记录已经修改的属性。
    /// 在子类中可以用代码片段 propfullc 来快速建立属性。
    /// </summary>
    public abstract class ModelWithState : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;

        private readonly List<string> changedProperties = new List<string>();
        private object listLocker = new object();
        /// <summary>
        /// 通知属性值已更改
        /// </summary>
        /// <param name="propertyName"></param>
        public virtual void OnPropertyChanged(string propertyName)
        {
            lock (listLocker)
            {
                if (!changedProperties.Contains(propertyName))
                {
                    changedProperties.Add(propertyName);
                }
            }
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        /// <summary>
        /// 当前实例的状态设为“未更改”
        /// </summary>
        public void AcceptChanges()
        {
            lock (listLocker)
            {
                changedProperties.Clear();
            }
        }
        /// <summary>
        /// 是否有变化
        /// </summary>
        /// <returns></returns>
        public bool HasChanges()
        {
            lock (listLocker)
            {
                return changedProperties.Count > 0;
            }
        }
        /// <summary>
        /// 获取已经更改的属性
        /// </summary>
        /// <returns></returns>
        public string[] GetChangedProperties()
        {
            lock (listLocker)
            {
                return changedProperties.ToArray();
            }
        }
    }
}
